package com.tiantianyuegou.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.StringUtils;
import com.tiantianyuegou.util.Tools;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 忘记密码
 */
public class ForgetPwdActivity extends BaseActivity implements View.OnClickListener,TextWatcher {
    private EditText edt_phone, edt_getcode;
    private Button btn_next, btn_getcode;
    private TimeCount timeCount;
    private String code, phone;
    private String vCode;
    private LoadingDialog loadingDialog;
    private String TAG = "ForgetPwdActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_pwd);
        Tools.changeSystemBar(this);
        setTitle(R.string.forgetpwd_title);
        initViews();
    }

    @Override
    public void findViewByIds() {
        edt_phone = (EditText) findViewById(R.id.edt_phone);
        edt_getcode = (EditText) findViewById(R.id.edt_getcode);
        btn_next = (Button) findViewById(R.id.btn_forget_next);
        btn_getcode = (Button) findViewById(R.id.btn_getcode);

        edt_getcode.addTextChangedListener(this);
        edt_phone.addTextChangedListener(this);

    }

    @Override
    public void initListener() {
        loadingDialog = new LoadingDialog(this);
        timeCount = new TimeCount(this, 60000, 1000);

        String phone = edt_phone.getText().toString().trim();
        String getCode = edt_getcode.getText().toString().trim();
        btn_next.setOnClickListener(this);
        btn_getcode.setOnClickListener(this);

    }

    @Override
    public void initData() {

    }
    public void launchActivity() {
        code = edt_getcode.getText().toString().trim();
        phone = edt_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showMsg("请输入手机号码");
            return;
        } else if (!StringUtils.checkPhone(phone)) {
            showMsg("手机号码格式错误");
            return;
        }
        if (TextUtils.isEmpty(code)) {
            showMsg("请输入验证码");
            return;
        }
        if (!code.equals(vCode)) {
            showMsg("验证码错误");
            return;
        }
        Intent next = new Intent();
        next.putExtra("vcode", vCode);
        next.putExtra("phone", phone);
        next.setClass(ForgetPwdActivity.this, ReSetActivity.class);
        if (getIntent().hasExtra("type")) {
            next.putExtra("type", getIntent().getStringExtra("type"));
        }
        startActivityForResult(next, Constant.FORGETPWD_REQUEST);
//        finish();

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==Constant.FORGETPWD_REQUEST){
            if(resultCode==Constant.FORGETPWD_RESULT){
                Intent intent=new Intent();
                intent.putExtra("type",data.getStringExtra("type"));
                setResult(Constant.FORGETPWD_RESULT1,intent);
                finish();
            }
        }
    }
    public void getCode() {
//        if (!NetworkUtils.isNetworkAvailable(this)) {
//            showMsg("请检查您的网络");
//            return;
//        }
        code = edt_getcode.getText().toString().trim();
        phone = edt_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showMsg("请输入手机号码");
            return;
        }
        if (!StringUtils.checkPhone(phone)) {
            showMsg("手机号码格式错误");
            return;
        }

        loadingDialog.showDialog();
        loadingDialog.setMsg("正在获取验证码");

        RequestParams params = new RequestParams();
//        TODO 需换成真正的字段名称
        params.addBodyParameter("tcMobile", phone);
        params.addBodyParameter("type", 1+"");
        Log.e("TAG", "phone=" + phone);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.GET_CODE, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                Log.e(TAG, "onSuccess response.result  "
                        + response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("获取失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            vCode = jsonObject.getString("vcode");
                            Log.e("验证码=", vCode);
                            timeCount.start();
                        } else if (code.equalsIgnoreCase("104")) {
                            showMsg("手机号码未注册");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                showMsg("当前网络不可用，请检查网络设置");
            }
        });

    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_forget_next:
                launchActivity();
                break;
            case R.id.btn_getcode:
                getCode();
                break;
        }

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        phone = edt_phone.getText().toString().trim();
        code = edt_getcode.getText().toString().trim();
        System.out.println("-----------code=" + code + "-------phone=" + phone);
        if (phone != null && code != null && !"".equals(phone) && !"".equals(code)) {
            btn_next.setEnabled(true);
            btn_next.setAlpha(1.0f);
        } else {
            btn_next.setEnabled(false);
            btn_next.setAlpha(0.5f);
        }

    }
    /**
     * 时间计时类
     */
    class TimeCount extends CountDownTimer {
        Activity activity;

        public TimeCount(Activity activity, long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            this.activity = activity;
        }

        /**
         * 计时过程
         *
         * @param millisUntilFinished
         */
        @SuppressLint("NewApi")
        @Override
        public void onTick(long millisUntilFinished) {
            btn_getcode.setClickable(false);
            btn_getcode.setBackground(activity.getResources().getDrawable(R.drawable.btn_getcode_timecount_bg));
            btn_getcode.setTextColor(getResources().getColor(R.color.textcolor_3));
            btn_getcode.setText(millisUntilFinished / 1000 + "S后重发");
        }

        /**
         * 计时完毕时触发
         */
        @SuppressLint("NewApi")
        @Override
        public void onFinish() {
            btn_getcode.setText(R.string.register_get_code);
            btn_getcode.setClickable(true);
            btn_getcode.setBackground(activity.getResources().getDrawable(R.drawable.btn_getcode_bg));
            btn_getcode.setTextColor(getResources().getColor(R.color.bg_button_normal));

        }
    }
}
